const Koa = require('koa');
const KoaRouter = require('koa-router');
const KoaStatic = require('koa-static');
const KoaBody = require('koa-body');
const path = require('path');
const fs = require('fs');

const StaticPath = path.join(__dirname, 'public');
const uploadPath = path.join(StaticPath, 'upload');

// 如果上传文件不存在，我们就创建它
if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
}

const app = new Koa();
const router = new KoaRouter();

const users = [
    {
        id: '1000',
        username: 'zhangsan',
        password: '123456',
    },
    {
        id: '1001',
        username: 'lisi',
        password: '123456',
    },
    {
        id: '1002',
        username: 'wangwu',
        password: '123456',
    },
    {
        id: '1003',
        username: 'zhaoliu',
        password: '123456',
    },
];

router.get('/login', async (ctx) => {
    // 读取参数
    // 调用 Model 层，获取数据(数据查询的数据)
    // 拿到了数据，再交给模板引擎，根据拿到的数据，渲染出 HTML 结构
    // ctx.body = ctx.query;
});

router.get('/users', async (ctx) => {
    // 获取查询参数
    const { username } = ctx.query;
    if (!username) {
        ctx.body = {
            code: 400,
            message: '请输入用户名',
        };
        return;
    }

    if (!/^[\w]{6,20}$/.test(username)) {
        ctx.body = {
            code: 400,
            message: '用户长度必须在 6 到 20 之间',
        };
        return;
    }

    if (users.findIndex((item) => item.username === username) === -1) {
        ctx.body = {
            code: 400,
            message: '用户未注册',
        };
        return;
    }

    ctx.body = {
        code: 200,
        message: '验证成功',
    };
});

router.post('/upload', async (ctx) => {
    console.log('ctx.request.files', ctx.request.files);
    const file = ctx.request.files.myfile;
    const targetFilename = Date.now() + file.name;

    const filePath = file.path;
    const absolutePath = path.join(uploadPath, targetFilename);

    // 读流和写流
    const readStream = fs.createReadStream(filePath);
    const writeStream = fs.createWriteStream(absolutePath);

    // 开始流水
    readStream.pipe(writeStream);

    // 上传成功
    ctx.body = {
        code: 200,
        data: {
            url: `http://localhost:8888/upload/${targetFilename}`,
        },
        message: '上传成功',
    };
});

app.use(KoaStatic(StaticPath));
app.use(
    KoaBody({
        multipart: true,
    })
);
app.use(router.routes());

app.listen(8888, () => {
    console.log('Server running at http://localhost:8888');
});
